//
//  PhotoFramePortraitViewController.m
//  PhotoFrame
//
//  Created by William on 11-5-5.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PhotoFramePortraitViewController.h"
#import "CalendarUtils.h"
#import "CalendarUtils.h"


@implementation PhotoFramePortraitViewController
@synthesize calendarObject;
@synthesize lastMonthCalendarObject;
@synthesize calendar;
@synthesize minuteTimer;
@synthesize ampmImageView;
@synthesize hoursImageView;
@synthesize minutesImageView;
@synthesize monthsImageView;
@synthesize yearLabel;
@synthesize colonImageView;
@synthesize photoImageView;
@synthesize weekdayImageViewCache;
@synthesize dayImageViewCache;
@synthesize dayCache;
@synthesize lastDayCache;
@synthesize colonStatus;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
    self.minuteTimer = timer;
	
	[self setTime];
	[self setDate];
	[self setMonth];
	[self setYear];
	
	[super viewDidLoad];
	
}

#pragma mark -
#pragma mark Temporal updates

- (void)setMinuteTimer:(NSTimer *)newTimer {
	
	if (minuteTimer != newTimer) {
		[minuteTimer invalidate];
		minuteTimer = newTimer;
	}
}

- (void) setColon {
	colonStatus = !colonStatus;
	[colonImageView setHidden:colonStatus];
}

- (void) setTime {
	NSString *ampmName = nil;
	NSString *hourName = nil;
	NSString *minuteName = nil;
	if (calendarObject.hour >= 12) {
		ampmName = @"img_pm.png";
		if (calendarObject.hour > 12) {
			hourName = [NSString stringWithFormat:@"%@%02d.png", @"img_time_s", calendarObject.hour - 11];
		} else {
			hourName = [NSString stringWithFormat:@"%@%02d.png", @"img_time_s", calendarObject.hour + 1];
		}
	} else {
		ampmName = @"img_am.png";
		hourName = [NSString stringWithFormat:@"%@%02d.png", @"img_time_s", calendarObject.hour + 1];
	}
	minuteName = [NSString stringWithFormat:@"%@%02d.png", @"img_time_s", calendarObject.minute + 1];
	
	[ampmImageView setImage: [UIImage imageNamed: ampmName]];
	[hoursImageView setImage: [UIImage imageNamed: hourName]];
	[minutesImageView setImage: [UIImage imageNamed: minuteName]];
}

- (void) setDate {
	CalendarUtils *calendarUtils = [[CalendarUtils alloc] init];
	
	int count = [calendarObject numOfDay];
	int weekday = [calendarUtils getWeekdayWithYear:calendarObject.year month:calendarObject.month day:1];
	
	[calendarUtils release];
	
	NSLog(@"Week day : %i", weekday);
	
	int weekdayX = 835;
	int weekdayY = 42;
	int dayX = 870;
	int dayY = 35;
	BOOL isHoliday = NO;
	BOOL isToday = NO;
	NSMutableArray *tmpWeekdayArray = [[NSMutableArray alloc] init];
	self.weekdayImageViewCache = tmpWeekdayArray;
	[tmpWeekdayArray release];
	NSMutableArray *tmDayImageViewArray = [[NSMutableArray alloc] init];
	self.dayImageViewCache = tmDayImageViewArray;
	[tmDayImageViewArray release];
	NSMutableArray *tmDayArray = [[NSMutableArray alloc] init];
	self.dayCache = tmDayArray;
	[tmDayArray release];
	if (lastMonthCalendarObject == nil) {
		self.lastMonthCalendarObject = self.calendarObject;
	}
	for (int i = 1; i < count + 1; i++) {
		if (i == 16) {
			weekdayX += 100;
			weekdayY = 42;
			dayX += 100;
			dayY = 35;
		}
		weekdayY += 35;
		dayY += 35;
		
		isToday = [self isToday:calendarObject thatDay:i];
		isHoliday = [self isHoliday:weekday];
		int photoSerialNum = [self getPhotoSerialNum:weekday];
		NSString *photoPrefix = [self getPhotoPrefix:isToday isHoliday:isHoliday];
				
		weekday = weekday == 7 ? 1: ++weekday;
				
		NSString *dayOfWeekName = [NSString stringWithFormat:@"%@%02d.png", photoPrefix, photoSerialNum];
		UIImageView *dayOfWeekImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:dayOfWeekName]];
		[dayOfWeekImageView setAlpha:0.5f];
		[dayOfWeekImageView setFrame:CGRectMake(weekdayX, weekdayY, 25, 11)];
		if (isToday == YES) {
			lastDayCache = i;
			[dayOfWeekImageView setAlpha:1.0f];
		}
		[weekdayImageViewCache addObject:dayOfWeekImageView];
		[self.view addSubview:dayOfWeekImageView];
		
		[dayOfWeekImageView release];
		
		// load day
		NSString *dayName = [NSString stringWithFormat:@"%@%02d.png", isHoliday == YES ? @"img_holiday_s" : @"img_weekday_s", i];
		UIImageView *dayImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:dayName]];
		[dayImageView setAlpha:0.5f];
		[dayImageView setFrame:CGRectMake(dayX, dayY, 22, 20)];
		if (isToday == YES) {
			[dayImageView setAlpha:1.0f];
		}
		[dayImageViewCache addObject:dayImageView];
		[dayCache addObject:[NSNumber numberWithInt:i]];
		[self.view addSubview:dayImageView];
		
		[dayImageView release];
	}
}

- (BOOL) isToday:(CalendarObjectDTO *)dto thatDay:(int)day {
	return dto.day == day ? YES : NO;
}

- (BOOL) isHoliday:(int)weekday {
	BOOL isHoliday = NO;
	switch (weekday) {
		case 1:
			isHoliday = YES;
			break;
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
			break;
		case 7:
			isHoliday = YES;
	}
	
	return isHoliday;
}
							 
- (int) getPhotoSerialNum:(int)weekday {
	int photoSeriaNum = 0;
	
	if (weekday == 1) {
		photoSeriaNum = 7;
	} else {
		photoSeriaNum = weekday - 1;
	}
	
	return photoSeriaNum;
}
- (NSString*) getPhotoPrefix:(BOOL)isToday isHoliday:(BOOL)isHoliday {
	NSString *photoPrefix = @"";
	if (isToday) {
		
		
		if (isHoliday) {
			photoPrefix = @"img_sholiday_r_s";
		} else {
			photoPrefix = @"img_sweekday_r_s";
		}
	} else {
		if (isHoliday) {
			photoPrefix = @"img_holiday_r_s";
		} else {
			photoPrefix = @"img_weekday_r_s";
		}
	}
	
	return photoPrefix;
}
							   

- (void) setMonth {
	NSString *monthName = [NSString stringWithFormat:@"%@%02d.png", @"img_month_r_s", calendarObject.month];
	[monthsImageView setImage:[UIImage imageNamed:monthName]];
}

- (void) setYear {
	[yearLabel setText:[NSString stringWithFormat:@"%d", calendarObject.year]];
}

- (void)updateTime:(NSTimer *)timer {
	if (calendarObject != nil) {
		//[calendarObject release];
		self.calendarObject = nil;
	}
	
	CalendarUtils *utils = [[CalendarUtils alloc] init];
	CalendarObjectDTO *tmpCalendarObject = [utils getCalendarInfo];
	self.calendarObject = tmpCalendarObject;
	[tmpCalendarObject release];
	[utils release];
	
	// refresh all date setting when modified the year
	if (lastMonthCalendarObject.year != calendarObject.year) {
		lastMonthCalendarObject.year = calendarObject.year;
		[self setYear];
		[self setMonth];
		for (int i = [dayCache count] - 1; i >= 0; i--) {
			UIImageView *weekdayImageView = [weekdayImageViewCache objectAtIndex:i];
			[weekdayImageView removeFromSuperview];
			[weekdayImageViewCache removeObjectAtIndex:i];
			
			UIImageView *dayImageView = [dayImageViewCache objectAtIndex:i];
			[dayImageView removeFromSuperview];
			[dayCache removeObjectAtIndex:i];
		}
		[self setDate];
	} else {
		if (lastMonthCalendarObject.month != calendarObject.month) {
			lastMonthCalendarObject.month = calendarObject.month;
			[self setMonth];
			for (int i = [dayCache count] - 1; i >= 0; i--) {
				UIImageView *weekdayImageView = [weekdayImageViewCache objectAtIndex:i];
				[weekdayImageView removeFromSuperview];
				[weekdayImageViewCache removeObjectAtIndex:i];
				
				UIImageView *dayImageView = [dayImageViewCache objectAtIndex:i];
				[dayImageView removeFromSuperview];
				[dayCache removeObjectAtIndex:i];
			}
			
			[self setDate];
		} else {
			if (lastMonthCalendarObject.day != calendarObject.day) {
				lastMonthCalendarObject.day = calendarObject.day;
				
				NSNumber *index = [dayCache objectAtIndex:calendarObject.day - 1];
				CalendarUtils *calendarUtils = [[CalendarUtils alloc] init];
				int weekday = [calendarUtils getWeekdayWithYear:calendarObject.year month:calendarObject.month day:[index intValue]];
				int lastSelectedWeekday = [calendarUtils getWeekdayWithYear:calendarObject.year month:calendarObject.month day:lastDayCache];
				[calendarUtils release];
				
				UIImageView *weekdayImageView = [weekdayImageViewCache objectAtIndex:calendarObject.day - 1];
				
				BOOL isHoliday = [self isHoliday:weekday];
				int photoSerialNum = [self getPhotoSerialNum:weekday];
				NSString *photoPrefix = [self getPhotoPrefix:YES isHoliday:isHoliday];
				
				NSString *dayOfWeekName = [NSString stringWithFormat:@"%@%02d.png", photoPrefix, photoSerialNum];
				[weekdayImageView setImage:[UIImage imageNamed:dayOfWeekName]];
				
				UIImageView *preSelectedWeekdayImageView = [weekdayImageViewCache objectAtIndex:lastDayCache - 1];
				
				isHoliday = [self isHoliday:lastSelectedWeekday];
				photoSerialNum = [self getPhotoSerialNum:lastSelectedWeekday];
				photoPrefix = [self getPhotoPrefix:NO isHoliday:isHoliday];
				dayOfWeekName = [NSString stringWithFormat:@"%@%02d.png", photoPrefix, photoSerialNum];
				[preSelectedWeekdayImageView setImage:[UIImage imageNamed:dayOfWeekName]];
				
				self.lastDayCache = [index intValue];
			}
		}
	}
    
	[self setColon];
	[self setTime];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	self.calendarObject = nil;
	self.lastMonthCalendarObject = nil;
	self.weekdayImageViewCache = nil;
	self.dayImageViewCache = nil;
	self.dayCache = nil;
}


- (void)dealloc {
	[calendarObject release];
	[lastMonthCalendarObject release];
	[weekdayImageViewCache release];
	[dayImageViewCache release];
	[dayCache release];
    [super dealloc];
}


@end
